package com.powerhua.fms.web;

import com.powerhua.core.utils.FileContentUtils;
import com.powerhua.core.utils.WebPathUtils;
import com.powerhua.core.web.IServletAction;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author yanyi.xu
 */
public class FileMainPageAction implements IServletAction {
    
    private static String MODEL = "file";
    private static String[] MAIN_CONTENTS = new String[]{
        "index_content/list"
    };

    @Override
    public String doAction(HttpServletRequest request) {

        String action = request.getParameter("act");

        if ("main".equals(action)) {
            return getMainPageContent();
        } else if ("deploy".equals(action)) {
            String[] workflowPages = new String[]{
                "index_content/WorkflowDefUpload"
            };
            return getPageContent(workflowPages);
        } else {
            return "";
        }
    }

    /**
     * 
     * @return
     */
    private String getMainPageContent() {
        StringBuffer result = new StringBuffer("");
        String path = WebPathUtils.getWebContentPath();
        String pathTmp = path + MODEL + "/index.html";
        String content = FileContentUtils.getTextFileString(pathTmp, "UTF-8");

        /*
         * 内容
         */
        String compStr = getPageContent(MAIN_CONTENTS);

        /*
         * 替换
         */
        result.append(content.replaceFirst("\\<!-- replace with content -->", compStr));
        return result.toString();
    }

    /**
     * 
     * @param workflowPages
     * @return
     */
    private String getPageContent(String[] contents) {
        StringBuffer result = new StringBuffer("");
        String path = WebPathUtils.getWebContentPath();

        for (int i = 0; i < contents.length; i++) {
            String pathTmp = path + MODEL + "/" + contents[i] + ".html";
            String content = FileContentUtils.getTextFileString(pathTmp, "UTF-8");
            int start = content.indexOf("<body>");
            int end = content.indexOf("</body>");
            content = content.substring(start + 6, end);
            result.append(content);
        }

        return result.toString();
    }

}
